package com.feige.utils.aliyun;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import org.joda.time.DateTime;

import java.io.InputStream;

/**
 * @author feige
 */
public class AliyunOssHandler {

    private static final String BUCKET_NAME = "xiaofei-cloud-disk";

    private static final String ENDPOINT = "https://oss-cn-hangzhou.aliyuncs.com";

    public static final String BUCKET_URL = "https://xiaofei-cloud-disk.oss-cn-hangzhou.aliyuncs.com/";

    // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录RAM控制台创建RAM账号。

    private static final String ACCESS_KEY_ID = "LTAI4GHGpiWBG9Ev1AdLfCHB";

    private static final String ACCESS_KEY_SECRET = "ZnUV9scb5iJlnA3zgwONWN8JtLAXyt";
    /**
     * 上传文件到阿里云oss
     * @param objectName 文件名 /abc/a.jpg
     * @param is 输入流
     * @return
     */
    public static boolean upload(String objectName, InputStream is) {
        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        // 上传文件到指定的存储空间（bucketName）并将其保存为指定的文件名称（objectName）。
        ossClient.putObject(BUCKET_NAME, objectName, is);
        // 关闭OSSClient。
        ossClient.shutdown();
        return true;
    }

    public static String joinFileName(String type,String objectName){
        DateTime now = DateTime.now();
        int year = now.getYear();
        int month = now.getMonthOfYear();
        int day = now.getDayOfMonth();
        return type + "/" + year + "/" + month + "/" + day + "/" + objectName;
    }

    public static String joinFileName(String objectName){
        DateTime now = DateTime.now();
        int year = now.getYear();
        int month = now.getMonthOfYear();
        int day = now.getDayOfMonth();
        return year + "/" + month + "/" + day + "/" + objectName;
    }

    /**
     * 从oss获取文件输入流
     * @param objectName
     * @return
     */
    public static InputStream getFileInputStream(String objectName) {
        OSS ossClient = new OSSClientBuilder().build(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        try {
            OSSObject object = ossClient.getObject(BUCKET_NAME, objectName);
            return object.getObjectContent();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
